package com.example.common.dialog.loading;


import android.app.Activity;

import com.coszero.utilslibrary.app.AppManager;
import com.coszero.utilslibrary.utils.LogX;

import java.lang.ref.WeakReference;

/**
 * 请求弹窗
 *
 * @author duke
 */
public class LoadingDialogHelper {
    private static final String TAG = "ProgressDialogHelper";
    private static LoadingDialogHelper mDialogHelper;

    private LoadingProgressView myProgressDialog;
    /**
     * 存储临时的Activity
     */
    private WeakReference mContext;

    public static LoadingDialogHelper get() {
        if (mDialogHelper == null) {
            mDialogHelper = new LoadingDialogHelper();
        }
        return mDialogHelper;
    }

    /**
     * 销毁进度
     */
    public void destroy() {
        if (myProgressDialog != null && myProgressDialog.isShowing()) {
            myProgressDialog.dismiss();
            myProgressDialog = null;
            mContext = null;
            mDialogHelper = null;
        }
    }

    public void show() {
        Activity activity = AppManager.getAppManager().currentActivity();
        if (activity == null && activity.isFinishing()) {
            return;
        }
        mContext = new WeakReference(activity);
        if (mContext != null) {
            ((Activity) mContext.get()).runOnUiThread(() -> show(0));
        }
    }

    public void show(int theme) {
        Activity activity = (Activity) mContext.get();
        if (myProgressDialog != null && mContext != null) {
            myProgressDialog.cancel();
            myProgressDialog = null;
            LogX.w("###", "加载Dialog不是本类Dialog,销毁");
        }

        if (myProgressDialog == null) {
            Activity context = (Activity) mContext.get();
            if (context == null) {
                LogX.w(TAG, "context is null");
                return;
            }
            if (theme != 0) {
                myProgressDialog = new LoadingProgressView(context, theme);
            } else {
                myProgressDialog = new LoadingProgressView(context);
            }
            LogX.i(TAG, "初始化加载Dialog");
        }

        if (activity != null && !activity.isFinishing()) {
            myProgressDialog.show();
        }

    }

    public void dismiss() {
        if (myProgressDialog != null && myProgressDialog.isShowing()) {
            ((Activity) mContext.get()).runOnUiThread(() -> myProgressDialog.dismiss());
        }
    }
}
